package com.music.web.controller;

import java.util.List;
import java.util.prefs.Preferences;

import org.junit.runners.Parameterized.Parameter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.music.biz.AlbumBiz;
import com.music.biz.ShoppingCartBiz;
import com.music.biz.UserBiz;
import com.music.entity.Album;
import com.music.entity.ShoppingCart;
import com.music.entity.Tool;

@Controller
public class ShoppingController {
	
	@Autowired
	private ShoppingCartBiz shoppingCartBiz;
	@Autowired
	private AlbumBiz albumBiz;
	@Autowired
	private UserBiz userBiz;
	
	@RequestMapping("showShoppingCar")
	public String showShoppingCar(@RequestParam(defaultValue = "0", required = false)int uid,Model model){
		if(uid != 0){
			List<ShoppingCart> shoppingCarts =shoppingCartBiz.getShoppingCartsByUserId(uid);
			model.addAttribute("shoppingCarts", shoppingCarts);
			return "cart";
		}
		throw new RuntimeException("未登陆，请登陆");
	}
	
	@RequestMapping(value="/purchase",method=RequestMethod.POST)
	public String purchase(@RequestParam(defaultValue = "0", required = false)int uid,int aid,Model model){
		if(uid != 0){
			int id=shoppingCartBiz.getShoppingCarById(uid, aid);
			if(id != 0){
				shoppingCartBiz.updateSum(uid, aid);
			}else {
				ShoppingCart shoppingCart =new ShoppingCart();
				Album album =albumBiz.fetchById(aid);
				shoppingCart.setAlbum(album);
				shoppingCart.setUser(userBiz.getUserById(uid));
				shoppingCart.setQuantity(1);
				shoppingCartBiz.add(shoppingCart);
			}
			List<ShoppingCart> shoppingCarts =shoppingCartBiz.getShoppingCartsByUserId(uid);
			model.addAttribute("shoppingCarts", shoppingCarts);
			int conut=Tool.countSum(shoppingCarts);
			double price=Tool.countPrice(shoppingCarts);
			model.addAttribute("conut", conut);
			model.addAttribute("price", price);
			return "cart";
		}
		throw new RuntimeException("用户未登陆,无法购买");
	}
	
	@RequestMapping(value="/deleteShoppingCart",method=RequestMethod.POST)
	public String deleteShoppingCart(int id,int uid,Model model){
		shoppingCartBiz.deleteShoppingCart(id);
		List<ShoppingCart> shoppingCarts =shoppingCartBiz.getShoppingCartsByUserId(uid);
		model.addAttribute("shoppingCarts", shoppingCarts);
		int conut=Tool.countSum(shoppingCarts);
		double price=Tool.countPrice(shoppingCarts);
		model.addAttribute("conut", conut);
		model.addAttribute("price", price);
		return "cart";
	}
	
}
